package com.kawa.kemanage.service.impl;

import com.kawa.kemanage.entity.Favorites;
import com.kawa.kemanage.mapper.FavoritesMapper;
import com.kawa.kemanage.service.FavoritesService;
import com.kawa.kemanage.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Author: KAIyo
 * @Date: 2025/6/27 17:11
 * @Version: v1.0.0
 * @Description: TODO
 **/
@Service
public class FavoritesServiceImpl implements FavoritesService {

    @Autowired
    private FavoritesMapper favoritesMapper;

    @Override
    @Transactional
    public Result addFavorite(Long userId, Long contentId) {
        try {
            // 检查是否已经收藏
            if (favoritesMapper.checkFavorite(userId, contentId)) {
                return Result.error("已经收藏过了");
            }

            // 创建收藏记录
            Favorites favorites = new Favorites();
            favorites.setUserId(userId);
            favorites.setContentId(contentId);
            favorites.setCreateTime(new Date());

            // 保存收藏
            favoritesMapper.insert(favorites);
            return Result.success("收藏成功");
        } catch (Exception e) {
            return Result.error("收藏失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result cancelFavorite(Long userId, Long contentId) {
        try {
            // 检查是否已经收藏
            if (!favoritesMapper.checkFavorite(userId, contentId)) {
                return Result.error("未收藏该内容");
            }

            // 删除收藏记录
            favoritesMapper.delete(userId, contentId);
            return Result.success("取消收藏成功");
        } catch (Exception e) {
            return Result.error("取消收藏失败：" + e.getMessage());
        }
    }

    @Override
    public Result getFavoritesList(Long userId) {
        try {
            List<Favorites> favoritesList = favoritesMapper.selectByUserId(userId);
            return Result.success(favoritesList);
        } catch (Exception e) {
            return Result.error("获取收藏列表失败：" + e.getMessage());
        }
    }

    @Override
    public Result checkFavorite(Long userId, Long contentId) {
        try {
            boolean isFavorited = favoritesMapper.checkFavorite(userId, contentId);
            return Result.success(isFavorited);
        } catch (Exception e) {
            return Result.error("检查收藏状态失败：" + e.getMessage());
        }
    }
}

